package com.my.mytest.kt.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.my.mytest.R
import com.my.mytest.kt.bean.KtImgBean
import com.my.mytest.util.GlideRoundTransform
import com.my.mytest.util.GlideUtil

/**
 * Created by Android Studio.
 * User: mwb
 * Date: 2020/12/15 0015
 * Time: 下午 2:24
 * Describe:
 */
class KtRvAdapter(context: Context) : Adapter<KtRvAdapter.MyViewHolder>() {
    var callBack: CallBack? = null
    var imageData: ArrayList<KtImgBean> = ArrayList()
    var context: Context = context

    fun setImgeData(imageData: ArrayList<KtImgBean>) {
        this.imageData = imageData
        setImageSize()
    }

    fun setImageSize() {
        for (i in 0 until imageData.size) {
            GlideUtil.getImageSize(context, imageData[i].imgResource) { bean ->
                imageData[i].setImgHeight(bean.height)
                imageData[i].setImgWidth(bean.widht)

                notifyDataSetChanged()
            }
        }

    }


    fun setCallback(callBack: CallBack) {
        this.callBack = callBack
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        var view = View.inflate(parent.context, R.layout.item_card_view, null)
        return MyViewHolder(view)
    }

    override fun getItemCount(): Int {
        return imageData.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        if (imageData[position].height != 0 &&
                imageData[position].widht != 0) {

            val lp1: ViewGroup.LayoutParams = holder.iv.layoutParams
            lp1.width = context.resources.displayMetrics.widthPixels / 2
            val h: Float = imageData[position].height.toFloat()
            val w: Float = imageData[position].widht.toFloat()
            val ratio: Float = h / w
            lp1.height = (ratio * lp1.width).toInt()

            holder.iv.layoutParams = lp1
        }

        Glide.with(holder.itemView.context)
                .load(imageData[position].imgResource)
                .centerInside()
                .transform(CenterCrop(), GlideRoundTransform(context, 10))
                .into(holder.iv)

        if (callBack != null) {
            holder.iv.setOnClickListener {
                callBack!!.onClick(position)
            }
        }
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var iv: ImageView = itemView.findViewById(R.id.item_card_iv)
    }

    interface CallBack {
        fun onClick(positon: Int)
    }
}